package edu.its.dreamteam.web.components;

import org.apache.tapestry.Asset;
import org.apache.tapestry.ComponentResources;
import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.PageRenderSupport;
import org.apache.tapestry.annotations.AfterRender;
import org.apache.tapestry.annotations.BeforeRenderBody;
import org.apache.tapestry.annotations.BeginRender;
import org.apache.tapestry.annotations.Environmental;
import org.apache.tapestry.annotations.Parameter;
import org.apache.tapestry.annotations.SupportsInformalParameters;
import org.apache.tapestry.ioc.annotations.Inject;
import org.apache.tapestry.services.AssetSource;

@SupportsInformalParameters
public class Image
{
    @Environmental
    private PageRenderSupport _support;

    @Inject
    private ComponentResources _resources;

    /**
     * The image asset to render.
     */
    @Parameter(required = true, defaultPrefix = "literal")
    private String _src;

    @Parameter(required = false, defaultPrefix = "literal", value = "context")
    private String _domain;

    @Inject
    private AssetSource assetSource;

    @BeginRender
    void begin(MarkupWriter writer)
    {
        String clientId = _support.allocateClientId(_resources.getId());

        Asset image = assetSource.findAsset(null, _domain + ":" + _src, null);
        writer.element("img", "src", image.toClientURL(), "id", clientId);

        _resources.renderInformalParameters(writer);
    }

    @BeforeRenderBody
    boolean beforeRenderBody()
    {
        return false;
    }

    @AfterRender
    void after(MarkupWriter writer)
    {
        writer.end();
    }
}

